﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.Domain.Entities;
using System.Web.Mvc;
using WebNext.UI.Properties;
using WebNext.UI.Utils;

namespace WebNext.UI.Models.Tags
{
	public class TagsViewModel : MainViewModel
	{
		private List<TagViewModel> tags;

		public IEnumerable<TagViewModel> Tags
		{
			get { return this.tags; }
		}

		public TagViewModel NewTag
		{
			get;
			private set;
		}

		public void SetViewType(MainViewType viewType)
		{
			EntryType entryType = ViewTypeConverter.GetEntryTypeByViewType(viewType);
			this.ViewType = ViewTypeConverter.GetViewTypeByEntryType(entryType);
		}

		public TagsViewModel(IEnumerable<Tag> tags, bool isLogged) : base(isLogged)
		{
			this.NewTag = new TagViewModel(0, null, null);
			this.tags = new List<TagViewModel>(tags.Select(t => new TagViewModel(t)));

			this.ViewType = MainViewType.EditTags;

			this.PageTitle = string.Format(Resources.TitleFormat, RuntimeSettings.SitePrefix, Resources.EditTags);
			this.PageName = Resources.EditTags;
			this.PageDescription = Resources.AddRemoveModifyTags;
		}

		public void Merge(TagViewModel tagModel)
		{
			if (tagModel.Id == 0)
			{
				this.NewTag.UpdateFrom(tagModel);
			}
			else
			{
				TagViewModel existingTagModel = this.tags.FirstOrDefault(t => t.Id == tagModel.Id);
				if (existingTagModel != null)
				{
					existingTagModel.UpdateFrom(tagModel);
				}
				else
				{
					this.tags.Add(tagModel);
				}
			}
		}
	}
}